#include "add_message.h"
#include "ui_add_message.h"
#include "studentstore.h"
#include "student.h"
#include "utils.h"
#include "init.h"
#include <time.h>
#include <QMessageBox>

using namespace studentstore;
using namespace student;
using namespace utils;

add_Message::add_Message(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::add_Message) {
    ui->setupUi(this);
}

add_Message::~add_Message() {
    delete ui;
}

void add_Message::getData(Student *stu,int type) {
    this->stu = stu;
    this->type = type;
    if(type==2)
    {
        ui->label_2->hide();
        this->stu->ID=-2;
        strcpy(this->stu->name,"超级管理员");
        strcpy(this->stu->stu_id,"888888");
    }
}

void add_Message::on_pushButton_clicked() {
    FILE *file = openfile(studentDatPath, sizeof(Student)); //打开文件
    fseek(file, 0, SEEK_END);//fseek将文件指针指到文件末尾
    auto offset = ftell(file);//ftell得到文件从指针到文件头的大小（offset是文件总大小）
    int allstu = offset / sizeof(Student);
    QString str = ui->lineEdit->text();
    if (str == NULL)
    {
        QMessageBox::warning(this, "warning", "请输入用户ID！");
    }
    else if(!isDigitStr(str)&&str.toInt()!=-1&&str.toInt()!=-2)
    {
        QMessageBox::warning(this,"warning","输入不合法！");
    }
    else
    {
        int receiver_id = str.toInt();
        if((receiver_id>=0&&receiver_id<allstu)||((type==1||type==0)&&receiver_id==-1)||((type==0||type==2)&&receiver_id==-2))
        {
            QString str2 = ui->textEdit->toPlainText();
            string messageBody = string((const char *)str2.toLocal8Bit());
            if(str2==NULL||!judgeSpace(messageBody))
            {
                QMessageBox::warning(this,"warning","内容不能为空！");
            }
            else if(str2.length()<=20&str2.length()>=1)
            {
                Message* msg = new Message();
                time_t timep;
                time(&timep);
                msg->sendTime = timep;
                msg->sender_id = stu->ID;
                msg->receiver_id = receiver_id;
                strcpy(msg->messageBody, &messageBody[0]);
                addMessage(msg);
                QMessageBox::warning(this,"提示","发送成功！");
                ui->lineEdit->clear();
                ui->textEdit->clear();
                delete msg;
                this->close();
            }
            else
            {
                QMessageBox::warning(this,"warning","内容长度不得超过20！");
            }
        }
        else
        {
            QMessageBox::warning(this,"warning","用户不存在！");
        }
    }
}
